#!/usr/bin/python

from elasticsearch import Elasticsearch
import sys
import json
import logging
import argparse
from subprocess import PIPE, Popen
from email.mime.text import MIMEText


def getOverlappedFiles(stream):
    process = Popen('ac stat -o -f1 -s ' + stream, shell=True, stdout = PIPE, stderr = PIPE)
    out, err = process.communicate()
    errorcode = process.returncode
    if errorcode != 0:
        print ("Find Error Messages: \n")
        return (None, False)
    
    overlapFilesList = out.splitlines()    
    return (overlapFilesList, True)

def getOverlappedFilesMappedToUser(overlapFilesList, product):
    
    #overlapFilesMapToUser = []
    if (True in overlapFilesList):
        overlapFilesList = list(overlapFilesList)
        overlapFilesList.remove(True)
    for overlapFiles in overlapFilesList:
        for overlapFile in overlapFiles:
            file = overlapFile.split()
            strFile = file[0].decode('ascii')     

            es = Elasticsearch(['http://si-portal-server.usd.lab.emc.com:9200/'])
            #es = Elasticsearch(['http://sles12-hanh8-dev-01.usd.lab.emc.com:9200/'])

            rs = es.search(index='logstash-siportal',
                           doc_type='promotion_file_ar_list',
                           body='{ \
                                  "query" : { \
                                      "bool" : { \
                                          "must" : [ \
                                              { \
                                               "match_phrase" : {"file" : "' + strFile + '"} \
                                              }, \
                                              { \
                                                "match_phrase" : {"product" : "' + product + '"} \
                                              } \
                                           ] \
                                       } \
                                  }, \
                                  "sort" : [{"timestamp" : {"order" : "desc"}}] \
                           }'
              
            )
            scroll_size = rs['hits']['total']
            promotion = rs['hits']['hits']
            
            if (scroll_size >= 1):
                print (promotion[0]['_source']['user'], promotion[0]['_source']['AR'], promotion[0]['_source']['file'], promotion[0]['_source']['domain_stream'], promotion[0]['_source']['promotion_request_id'])
                #item = [promotion[0]['_source']['user'], promotion[0]['_source']['AR'], promotion[0]['_source']['file'], promotion[0]['_source']['domain_stream'], promotion[0]['_source']['promotion_request_id']]
                #overlapFilesMapToUser.append(item)
    #return overlapFilesMapToUser


def formBody(overlapFilesMapToUser):
    
    body = "OverLapped Files:" + "\n\n"
    overlapFilesMapToUser.sort()
    for item in overlapFilesMapToUser:
        itemToStr = "  ".join(str(v) for v in item) + "\n\n"
        body += itemToStr
    return body 


def email(to, body):
    msg = MIMEText(body)
    msg["From"] = "eva.ou@emc.com"
    msg["To"] = to
    msg["Subject"] = "OverLapped files, please merge them."
    p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
    p.communicate(msg.as_string().encode('utf-8'))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s','--stream', type=str, help="stream names. e.g -m upc-Unity-int,upc-nextUnity-mcs")
    parser.add_argument('-p','--product', type=str, help="product name. e.g -p Thunderbird_SP1")
    #parser.add_argument('-t','--to', type=str, help="who will receive this email")
    overlapFiles = getOverlappedFiles(parser.parse_args().stream)
    if (False in overlapFiles):
        print ("No overlap files, or accurev is not logged in.")
        return
    getOverlappedFilesMappedToUser(overlapFiles, parser.parse_args().product)
    #overlapFilesMapToUser = getOverlappedFilesMappedToUser(overlapFiles)
    #body = formBody(overlapFilesMapToUser)
    #email(parser.parse_args().to, body)


if __name__ == '__main__':
    main()
